package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜品业务层
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource(name = "dishMapper")
    DishMapper dishMapper;
    @Resource(name = "dishFlavorMapper")
    DishFlavorMapper dishFlavorMapper;
    @Resource(name = "setmealDishMapper")
    SetmealDishMapper setmealDishMapper;
    @Resource(name = "setmealMapper")
    SetmealMapper setmealMapper;
    @Resource(name = "shoppingCartMapper")
    ShoppingCartMapper shoppingCartMapper;

    /**
     * 新增菜品
     * @param dishDTO 菜品数据传输对象，包含菜品信息和口味信息
     * @return 返回true表示新增成功，返回false表示新增失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        try {
            dishMapper.addDish(dish);
            // 如果有口味信息，则一并添加到数据库
            if (dishDTO.getFlavors().size() != 0 && !dishDTO.getFlavors().isEmpty()) {
                List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
                // 给每个口味对象设置菜品ID
                dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
                dishFlavorMapper.addDishFlavor(dishFlavorList);
            }
        } catch (Exception exception) {
            log.info("新增菜品执行异常：{}", exception);
            return false;
        }
        return true;
    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO 菜品分页查询条件对象
     * @return 返回分页查询结果
     */
    @Override
    public PageResult selDishAll(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 根据条件查询所有菜品
        List<DishVO> dishVOList = dishMapper.selDishAll(dishPageQueryDTO);
        Page<DishVO> dishVOPage = (Page<DishVO>) dishVOList;
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
    }

    /**
     * 通过id查询菜品
     * @param id 菜品ID
     * @return 返回菜品详情，包括口味信息
     */
    @Override
    public DishVO selDishById(Long id) {
        DishVO dishVO = dishMapper.selDishById(id);
        // 查询该菜品的所有口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selDishFlavorById(id);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId 分类ID
     * @return 返回属于该分类的所有菜品
     */
    @Override
    public List<Dish> selDishByCategoryId(Long categoryId) {
        return dishMapper.selDishByCategoryId(categoryId);
    }

    /**
     * 菜品启用/禁用
     * @param status 状态值，1为启用，0为禁用
     * @param id 菜品ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateTimeDish(dish);
        // 更新包含该菜品的套餐状态
        setmealMapper.updateTimeSetmealStatusByDishId(dish);
    }

    /**
     * 批量删除菜品
     * @param idList 要删除的菜品ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delDishById(List<Long> idList) {
        // 判断菜品是否在售，若在售则不能删除
        idList.forEach(id -> {
            if (dishMapper.selDishById(id).getStatus() == 1)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        });

        // 判断菜品是否被套餐包含，若被包含则不能删除
        List<SetmealDish> list = setmealDishMapper.selAllByDishId(idList);
        if (list.size() > 0)
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        // 删除菜品口味信息，然后删除菜品本身
        dishFlavorMapper.delDishFlavorByDishId(idList);
        dishMapper.delDishById(idList);
    }

    /**
     * 修改菜品信息
     * @param dishDTO 要修改的菜品的信息，包括菜品本身和口味信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTime(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 更新菜品信息
        dishMapper.updateTimeDish(dish);
        List<Long> list = new ArrayList<>();
        list.add(dishDTO.getId());
        // 先删除旧的口味信息
        dishFlavorMapper.delDishFlavorByDishId(list);
        // 添加新的口味信息
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (!dishFlavorList.isEmpty()) {
            dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.addDishFlavor(dishFlavorList);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selDishByCategoryId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selDishFlavorById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}


